<?php
class AccountController extends Controller{

	const USER_GOOGLE = 'google';
	const USER_HOST = 'host';
	private $email = null;
	private $_identity;
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to access 'index' and 'view' actions.
				'actions'=>array('login','register','sure','forget','password','active','favor','ajaxlogin','renren','flash'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated users to access all actions
				'actions'=>array('password','logout','favor'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
				'message'=>'您无权访问',
			),
		);
	}
	public function actionLogin(){
		//dbg($_COOKIE);
		$this->layout = 'login';
		$loginFormModel = new AccountForm('login');
		 if(isset($_POST['ajax']) && $_POST['ajax'] === 'login-form' ){
			echo CActiveForm::validate($loginFormModel);
			Yii::app()->end();
		 }
		if(isset($_POST['AccountForm']))
		{
			$loginFormModel->attributes=$_POST['AccountForm'];
			$loginFormModel->password = md5($loginFormModel->password);
			// validate user input and redirect to the previous page if valid
			if($loginFormModel->validate() && $loginFormModel->login())
				$this->redirect(Yii::app()->user->returnUrl);
			else
				$loginFormModel->addError('','邮箱和密码不匹配！');
		}
		$this->render('login',array('loginFormModel'=>$loginFormModel));
	}
	public function actionAjaxlogin(){

		$email = NC::_p('AccountForm_email','');
		$password = NC::_p('AccountForm_password','');
		$id = NC::_p('domid','');
		unset($_POST);
		$_POST['AccountForm']['email']=urldecode($email);
		$_POST['AccountForm']['password']=urldecode($password);
		$loginFormModel = new AccountForm('login');
		$res = CActiveForm::validate($loginFormModel);
		$res = json_decode($res,true);
		if(!empty($res)){
			NC::json(false,$res);
			Yii::app()->end();
		}
		if(isset($_POST['AccountForm']))
		{
			$loginFormModel->attributes=$_POST['AccountForm'];
			$loginFormModel->password = md5($loginFormModel->password);
			if($loginFormModel->login())
				NC::json(true,'',null,$id);
			else{
				NC::json(false,array('error'=>'用户名和密码不对'));
			}
		}
	}
	public function actionLoginout(){
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	public function actionRegister(){
		$this->layout = 'login';
		$sure = false;
		$userModelAr = new User('register');
		 if(isset($_POST['ajax']) && $_POST['ajax'] === 'register-form' ){
			echo CActiveForm::validate($userModelAr);
			Yii::app()->end();
		 }
		if(isset($_POST['User']))
		{
			$userModelAr->attributes = $_POST['User'];
			$this->email = $_POST['User']['email'];
			if($userModelAr->save()){
				Profiles::model()->saveProfiles($userModelAr->user_id);
				EmailQueue::model()->saveEmailQueue($userModelAr->attributes,'register');
				//设置验证邮箱的cookie时间,10分钟内有效
				NcCookie::setCookie("active",$this->email,10*60,'/');
				$this->redirect('/account/active');
			}
		}
		$this->render('register',array('userModelAr'=>$userModelAr,'sure'=>$sure));
	}
	
	public function actionActive(){
		$email = NcCookie::getCookie("active");
		if($email){
			$userDomain = @explode('@',$email);
			if(isset($userDomain[1])){
				switch($userDomain[1]){
					case 'gmail.com':
						$userDomain['1'] = "google.com";
					break;
				}
				$this->render('active',array('type'=>'send','email'=>$userDomain));
			}
		}
	}
	public function actionLogout(){
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	public function actionSure(){
		//1、验证cookie时间
		$email = NcCookie::getCookie("active");
		if(!$email){$this->render('error',array('error'=>'timeout'));exit;}
		//2、验证url的合法性
		$userId = (int)NC::_g('id',0);$md5Message = urldecode(NC::_g('active',''));
		if(!$userId || !$md5Message){$this->render('error',array('error'=>'urlinvalided'));exit;}
		//3、验证数据库是否存在这条记录
		$emailQueue = EmailQueue::model()->findByAttributes(array('user_id'=>$userId,'email'=>$email,'type'=>'register'));
		if(empty($emailQueue)){$this->render('error',array('error'=>'valided'));exit;}
		if($userId != $emailQueue->user_id || $md5Message != $emailQueue->md5_message){$this->render('error',array('error'=>'valided'));exit;}
		//4、验证通过，更新user表
		$user = new User();
		$result = $user->findByPk($userId,array('condition'=>'is_active = 0'));
		if($result){
			$re = $result->saveAttributes(array('is_active'=>1));
			//让其登录，发送邮箱和密码去验证登录
			User::login($result->email,$result->password);
			//自动初始化10个上游
			self::addUpper();
			$this->redirect('/account/favor');	
		}else{
			$this->render('active',array('type'=>'actived','email'=>$emailQueue->email));
		}
		//$this->render('sure',array('email'=>$this->email));
	}
	public function actionFavor(){
		//推荐的一些兴趣标签
		$diggFavor = Favor::model()->findAll(array('order'=>'user_count DESC','limit'=>'20'));
		$this->render('favor',array('diggFavor'=>$diggFavor));
	}
	public function actionForget(){
		$userModel = new User('forget');
		$emailModel = new EmailQueue('forget');
		$userEmail = null;
		$result = null;
		$msg = null;
		if(isset($_POST['ajax']) && $_POST['ajax'] === 'forget-form' ){
			echo CActiveForm::validate($emailModel);
			Yii::app()->end();
		 }
		if(isset($_POST['ajax']) && $_POST['ajax'] === 'password-form' ){
			//echo CActiveForm::validate($emailModel);
			echo CActiveForm::validate($userModel);
			Yii::app()->end();
		 }
		 
		if(isset($_POST['EmailQueue'])){
			//dbg($_POST);
			$result=$userModel->model()->findByAttributes(array('email'=>$_POST['EmailQueue']['email']));
			if($result&&$emailModel->saveEmailQueue($result->attributes,'forget')){
				$msg = "<span >修改密码的链接已发至您的邮箱，请及时查收。</span>";
			}else{
				$msg = "<span style='color:#EA5514;'>您输入的邮箱地址不存在！</span>";
			}
		}
		if(isset($_GET['go'])&&isset($_COOKIE['email'])){
			$emailInfo = $emailModel->model()->findByAttributes(array('md5_message'=>$_GET['go']));
			//$flag = $_GET['go']==md5(urlencode($_COOKIE['email']))&&$emailInfo?true:false;
			if($emailInfo){
				$result = $userModel->model()->findByAttributes(array('email'=>$emailInfo->email));
				$this->email = $emailInfo->email;
				$userId = $result->user_id;
				$this->redirect('/account/password/id/'.$userId);
			}else{
				$msg = "找回密码链接已过期，请重输入邮箱！";
			//	echo "<script>addError('找回密码链接已过期，请重输入邮箱！');window.location.href='/account/forget';closeError();</script>";
			}
		}
		if(isset($_POST['User'])){
			$tag = $userModel->updateByPk($user_id,array('password'=>md5($_POST['User']['password'])));
			$this->redirect('/account/login');
		}
		$this->render('forget',array('emailModel'=>$emailModel,'userEmail'=>$this->email,'userModel'=>$userModel,'msg'=>$msg));
	}
	public function actionPassword(){
		$sucess = false;
		$userModel = new User('resetpasswd');
		if(isset($_POST['User']) && isset($_GET['id'])){
			$userID = NC::_g('id','');
			if($userID){
				$userInfo = $userModel->model()->findByPk($userID);
				if($userInfo){
					$userModel->email = $userInfo->email;
				}
			}
			CActiveForm::validate($userModel);
			if(!$userModel->getErrors()){
				$password = md5($userModel->password);
				if(User::model()->updateByPk($userID,array('password'=>$password))){
					$sucess = "恭喜您，密码修改成功！";
				}else{
					$userModel->addError('password','抱歉，重设密码失败！');
				}
			}
			$this->render('password',array('userModel'=>$userModel,'email'=>$this->email,'sucess'=>$sucess));
			Yii::app()->end();
		 }
		 $id = isset($_GET['id'])?$_GET['id']:null;
		 if($id){
			 $userInfo = $userModel->model()->findByPk($id);
			 $this->email = $userInfo->email;
			 $userID = $id;
		 }elseif(isset($_GET['go'])){
			$emailInfo = EmailQueue::model()->findByAttributes(array('md5_message'=>$_GET['go']));
			//$flag = $_GET['go']==md5(urlencode($_COOKIE['email']))&&$emailInfo?true:false;
			if($emailInfo){
				$result = $userModel->model()->findByAttributes(array('email'=>$emailInfo->email));
				$this->email = $emailInfo->email;
				$userID = $result->user_id;
			}else{
				$sucess = "找回密码链接已过期，请重输入邮箱！,请 <a href='/account/forget'>重新找回密码</a>";
			}
		}

		
		$this->render('password',array('userModel'=>$userModel,'email'=>$this->email,'sucess'=>$sucess));
	}
	public static function addUpper(){
		$connection = Yii::app()->db;
		$sql = "select * from nc_user where user_id != ". Yii::app()->user->id ." order by issue_num DESC limit 10";
		$user = $connection->createCommand($sql)->queryAll();
		if(!empty($user)){
			foreach($user as $key=>$value){
				/*
				$upper = new Upper();
				$upper->upper_user_id = $value['user_id'];
				$upper->upper_user_name = $value['user_name'];
				$upper->user_id = Yii::app()->user->id;
				$upper->user_name = Yii::app()->user->name;
				$upper->upper_time = time();
				$upper->save();	
				*/
				Upper::addUpper($value['user_id']);
			}
		}
	}
	public function actionRenren(){
		$renrenClass = new Renren();
		//1、验证COOKIE
		$renrenCookie = $renrenClass->checkRenren();
		if(!$renrenCookie){$this->redirect('/account/login');exit;}
		//2、验证是否已绑定过
		$isBindUser = User::model()->find('password=\''.md5($renrenCookie['user_id']) . "' and user_type='renren' ");
		if($isBindUser){//已绑定，直接登录
			if($this->_identity===null)
			{
				$this->_identity=new UserIdentity($isBindUser->user_name,$isBindUser->password);
				$this->_identity->authenticate('renren',$isBindUser);
			}
			if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
			{
				$duration=$isBindUser->is_remember ? 3600*24*30 : 0; // 30 days
				Yii::app()->user->login($this->_identity,$duration);
				$this->redirect(Yii::app()->user->returnUrl);
			}
			Yii::app()->end();
		}
		//3、取信息
		$renrenInfo = $renrenClass->getInfo();
		//4、插入到数据库
		$register = $renrenClass->registerNC($renrenInfo);
		if($register){
			if($this->_identity===null)
			{
				$this->_identity=new UserIdentity($register->user_name,$register->password);
				$this->_identity->authenticate('renren',$register);
			}
			if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
			{
				$duration=$register->is_remember ? 3600*24*30 : 0; // 30 days
				Yii::app()->user->login($this->_identity,$duration);
				$returnUrl = Yii::app()->user->returnUrl;
				echo '<script type="text/javascript">window.location.href="'.$returnUrl.'"</script>"';
                exit;

			}
			
		}else{
			throw new CHttpException('登录失败',$register);
		}
		
	}

	public function actionFlash(){
		dbg($_POST);
	}
}

